<template>
  <div>
    <van-address-edit
      :area-list="areaList"
      :address-info="addressInfo"
      show-search-result
      :show-delete="showDelete"
      :search-result="searchResult"
      @save="onSave"
      @delete="onDelete"
      @change-detail="onChangeDetail"
      save-button-text="保存并使用"
      delete-button-text="删除收货地址"
    />


  </div>
</template>
<script>
  import customerService from '../../api/customerService';
  import areaList from '../../../../common/js/van-area';
  import {Dialog} from 'vant';
  export default {
    data() {
      return {
        showDelete:false,
        defaultAddr:'',
        addressInfo:{},
        addrId:'',
        areaList,
        searchResult: []
      }
    },

    methods: {
      _getDetail(){
        customerService.getAddrById({id:this.addrId}).then((rsp)=>{
          if(rsp.result) {
            let obj = rsp.obj;
            this.defaultAddr = obj.defaultAddr;
            this.addressInfo = {
              id:obj.id,
              name:obj.name,
              tel:obj.mobile,
              province:obj.province,
              city:obj.city,
              county:obj.area,
              addressDetail:obj.address,
              areaCode:obj.areaCode
            };
          }else {
            this.$toast(rsp.errorMsg);
          }
        }).catch((error)=>{
            this.$toast('getAddrById接口异常'+error);
        });
      },
      onSave(data) {
        var para ={
          mobile:data.tel,
          province:data.province,
          city:data.city,
          area:data.county,
          address:data.addressDetail,
          areaCode:data.areaCode,
          name:data.name
        };
        if(data.id) {
          para.id = data.id;
          para.defaultAddr = this.defaultAddr;
        }
        customerService.addAddr(para).then((rsp)=>{
          if(rsp.result) {
            this.$toast('新增地址成功');
            if(this.$route.query.addrId) {
              delete this.$route.query.addrId;
            }
            this.$nocacheRouter('/pay',this.$route.query);
        }else {
          this.$toast(rsp.errorMsg);
        }
      }).catch((error)=>{
          this.$toast('addAddr接口异常'+error);
      });
      },
      onDelete(data) {
        customerService.delAddr({id:data.id}).then((rsp)=>{
            if(rsp.result) {
            this.$toast('删除地址成功');
            if(this.$route.query.addrId) {
              delete this.$route.query.addrId;
            }
            this.$nocacheRouter('/addrList',this.$route.query);
          }else {
            this.$toast(rsp.errorMsg);
          }
        }).catch((error)=>{
            this.$toast('delAddr接口异常'+error);
        });
      },
      onChangeDetail(val) {
      }
    },
    mounted(){
      let query = this.$route.query;
      //edit addr
      if(query.addrId) {
        this.showDelete = true;
        this.addrId = query.addrId;
        this._getDetail();
      }
    }
  }
</script>
